package com.sudo.service.admin.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.sudo.common.constant.FileDirConstant;
import com.sudo.common.utils.LocalDateTimeUtil;
import com.sudo.common.utils.OperateImage;
import com.sudo.common.utils.PagedGridResult;
import com.sudo.dao.admin.entity.SysUser;
import com.sudo.dao.admin.entity.UserFile;
import com.sudo.dao.admin.mapper.SysUserMapper;
import com.sudo.dao.admin.mapper.UserFileMapper;
import com.sudo.service.admin.service.AdminBaseService;
import com.sudo.service.admin.service.UserFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

/**
 * @author 为道日损 2020-06-22 10:01
 * webSite：https://www.sudo.ren
 */
@Slf4j
@Service
public class UserFileServiceImpl extends AdminBaseService implements UserFileService {

    @Resource
    private UserFileMapper userFileMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Transactional(propagation = Propagation.REQUIRED ,rollbackFor = Exception.class)
    @Override
    public int addUserFile(String username ,String oldFileName,String newFileName,String logicalPosition) {
        UserFile userFile = new UserFile();
        userFile.setUsername(username);
        userFile.setOldName(oldFileName);
        userFile.setFileName(newFileName);
        userFile.setFilePath(logicalPosition);
        userFile.setUploadTime(LocalDateTimeUtil.getStandardDateTimeStr());
        return userFileMapper.insertSelective(userFile);
    }

    @Transactional(propagation = Propagation.SUPPORTS ,rollbackFor = Exception.class)
    @Override
    public PagedGridResult getAllFilesByPage(Integer page , Integer pageSize,
                                             String username, String startDate, String endDate) {
        PageHelper.startPage(page, pageSize);
        Example example = new Example(UserFile.class);
        example.orderBy("id").desc();
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(username)) {
            criteria.andEqualTo("username", username);
        }
        if (StringUtils.isNotBlank(startDate)) {
            criteria.andGreaterThanOrEqualTo("uploadTime", startDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            criteria.andLessThanOrEqualTo("uploadTime", endDate);
        }
        List<UserFile> sysUserList = userFileMapper.selectByExample(example);

        return setterPagedGrid(sysUserList ,page);
    }

    @Override
    public String uploadUseLogo(MultipartFile file, HttpServletRequest request, String username) {
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        Integer affectCount = null;
        String logicalPosition = null;
        try {
            // 原文件名
            String oldFileName = file.getOriginalFilename();
            // 新文件名
            String newFileName = getNewFileName(FileDirConstant.USER_INFO,oldFileName, username);
            // 相对地址文件
            String relativePositionFile = getRelativePositionFile(FileDirConstant.USER_INFO,newFileName, username);
            // 物理地址文件
            String physicalPositionFile = getPhysicalPositionFile(relativePositionFile);
            // 逻辑地址文件
            logicalPosition = getLogicalPosition(relativePositionFile);
            File outFile = new File(physicalPositionFile);
            if (null != outFile.getParentFile()) {
                //创建文件夹
                outFile.getParentFile().mkdirs();
            }
            //文件输出保存到目录
            fileOutputStream = new FileOutputStream(outFile);
            inputStream = file.getInputStream();
            IOUtils.copy(inputStream, fileOutputStream);

            JSONObject object = JSON.parseObject(request.getParameter("avatar_data"));
            OperateImage operateImage = new OperateImage(
                    object.getInteger("x"), object.getInteger("y"),
                    object.getInteger("width"),object.getInteger("height"));
            operateImage.setSrcPath(physicalPositionFile);
            // 裁剪图片将自己替换，所以srcPath和subPath相同，否则需要删除原图片，见下方finally
            operateImage.setSubPath(physicalPositionFile);
            operateImage.cut();
            affectCount = updateUserLogo(username,logicalPosition);
        } catch (Exception e) {
            affectCount = 0;
            log.error("用户头像上传失败：",e);
        }finally {
            if (null != fileOutputStream) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception ex) {
                    log.error("文件流关闭失败：",ex);
                }finally {
                    //删除原图片，这里因为替换了原图片，所以不用再删除
                    //outFile.delete();
                }
            }
        }
        if (affectCount > 0) {
            return logicalPosition;
        }else {
            return null;
        }
    }

    @Transactional(propagation = Propagation.REQUIRED ,rollbackFor = Exception.class)
    @Override
    public int updateUserLogo(String sessionUser, String logicalPosition) {
        Example example = new Example(SysUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", sessionUser);

        SysUser sysUser = new SysUser();
        sysUser.setProfilePhoto(logicalPosition);
        sysUser.setUpdateBy(sessionUser);
        sysUser.setUpdateTime(LocalDateTimeUtil.getStandardDateTimeStr());
        return sysUserMapper.updateByExampleSelective(sysUser,example);
    }

    @Override
    public void deleteFileByUsername(String username) {

    }

    @Override
    public int uploadCommonFile(MultipartFile file, String username){
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        Integer affectCount = null;
        try {

            // 原文件名
            String oldFileName = file.getOriginalFilename();
            // 新文件名
            String newFileName = getNewFileName(FileDirConstant.COMMON_FILE,oldFileName, username);
            // 相对地址文件
            String relativePositionFile = getRelativePositionFile(FileDirConstant.COMMON_FILE,newFileName, username);
            // 物理地址文件
            String physicalPositionFile = getPhysicalPositionFile(relativePositionFile);
            // 逻辑地址文件
            String logicalPosition = getLogicalPosition(relativePositionFile);

            File outFile = new File(physicalPositionFile);
            if (null != outFile.getParentFile()) {
                //创建文件夹
                outFile.getParentFile().mkdirs();
            }
            //文件输出保存到目录
            fileOutputStream = new FileOutputStream(outFile);
            inputStream = file.getInputStream();
            IOUtils.copy(inputStream, fileOutputStream);
            affectCount = addUserFile(username,oldFileName,newFileName,logicalPosition);
        } catch (Exception e) {
            affectCount = 0;
            log.error("文件上传失败：",e);
        }finally {
            if (null != fileOutputStream) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception ex) {
                    log.error("文件流关闭失败：",ex);
                }
            }
        }
        return affectCount;
    }
}
